package com.yanqu.road.server.manger.location;

import com.yanqu.road.logic.bussiness.servercenter.IpInfoBussiness;
import com.yanqu.road.entity.servercenter.IpInfo;
import com.yanqu.road.logic.redis.RedisIpToCity;
import com.yanqu.road.server.TempMgr;
import com.yanqu.road.server.GameServer;

import java.util.Map;

public class IpMgr extends TempMgr {

//	private static Map<String, IpInfo> ipInfoMap;

	@Override
	public boolean reload() {//reload不管，就是要写进去
		GameServer.getServerCommandExecutor().execute(() -> {
			Map<String, IpInfo> ipInfoMap = IpInfoBussiness.getIpInfo();
			RedisIpToCity.clearIpToCityInfo();        //先清掉以前的
			RedisIpToCity.setIpToCityInfo(ipInfoMap);  //从新设置新值
		});
		return true;
	}

	@Override
	public boolean reloadConfig() throws Exception {
		return true;
	}

	@Override
	public boolean reloadData() throws Exception {
		return true;
	}

	@Override
	public boolean init() {
		GameServer.getServerCommandExecutor().execute(() -> {
			if(!RedisIpToCity.getHasIpToCityInfo()){
				Map<String, IpInfo> ipInfoMap = IpInfoBussiness.getIpInfo();
				if(!RedisIpToCity.isLoadLock()) {
					RedisIpToCity.setIpToCityInfo(ipInfoMap);
					RedisIpToCity.deleteLoadLock();
				}
			}
		});
		return true;
	}

	@Override
	public boolean stop() {
		return false;
	}

	@Override
	public boolean save() {
		return false;
	}

	public static IpInfo getIpInfo(String ip) {
		if (ip == null) {
			return null;
		}
		String subIpStr = ip.substring(0, ip.lastIndexOf(".") + 1);
		return RedisIpToCity.getIpToCityInfo(subIpStr);
	}

//	public static IpInfo getIpInfo(String ip) {
//		String subIpStr = ip.substring(0, ip.lastIndexOf(".") + 1);
//		if (ipInfoMap != null) {
//			return ipInfoMap.get(subIpStr);
//		}
//		return null;
//	}
}
